package twentytwenty;

import java.util.Scanner;

/**
 * @Author: Spider Man
 * @Description:
 * @Date Created in 2020-09-26 11:50
 * @Modified By:
 */
public class Encryption {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("原文 :");
        String str = input.next();

        System.out.print("密码: K = ");
        int K = input.nextInt();

        StringBuilder ciphertext = new StringBuilder(""); // 创建新字符串存储密文

        for (int i = 0; i < str.length(); i++) {
            char temp = str.charAt(i);
            if (temp >= 65 && temp <= 90) { // 判断是否为大写字母
                ciphertext.append(encrypted(temp, K, 65, 26));
            }else if (temp >= 97 && temp <= 122){
                ciphertext.append(encrypted(temp, K, 97, 26));
            }else if (temp >= 48 && temp <= 57) { // 判断是否为数字
                ciphertext.append(encrypted(temp, K, 48, 10));
            }else {
                ciphertext.append(temp);
            }
        }
        System.out.println("密文 :" + ciphertext);
    }

    /**
     * 加密方法
     * @param ch 原文
     * @param key 密码
     * @param minAscii 48数字，65大写字母，97小写字母
     * @param length 长度区间
     * @return 加密的字符
     */
    public static char encrypted(char ch, int key, int minAscii, int length) {
        int temp = Integer.valueOf(ch);
        temp = (temp - minAscii + key) % length + minAscii;
        return (char) temp;
    }
}
